package fr.nts.framework.database.jpa.dao;

import java.util.List;

import javax.persistence.NoResultException;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.google.common.collect.Lists;

import fr.nts.framework.database.jpa.model.common.SimpleMenu;

/**
 * Un DAO manipulant les {@link SimpleMenu} avec JPA
 * 
 * @author sco
 * @version 1.0.0
 */
@Component
public class SimpleMenuDao extends AJPADao<SimpleMenu, Long>{
	
	private final static Logger log = LoggerFactory.getLogger(SimpleMenuDao.class);
	
	private final static String PARENT = "parentMenu";
	
	/*
	 * (non-Javadoc)
	 * @see fr.letrader.database.dao.ADao#getBoClass()
	 */
	@Override
	protected Class<SimpleMenu> getBoClass(){
		return SimpleMenu.class;
	}
	
	
	/**
	 * Récupère la liste des menu parent
	 * 
	 * @return Une liste de {@link SimpleMenu}
	 */
	public List<SimpleMenu> findAllParentMenus(){
		List<SimpleMenu> parentMenus = Lists.newArrayList();
		
    	CriteriaBuilder builder = getEntityManager().getCriteriaBuilder();
    	CriteriaQuery<SimpleMenu> query = builder.createQuery(getBoClass());
    	
    	// Requète de base: select * from T
    	Root<SimpleMenu> root = query.from(getBoClass());
    	query.where(builder.isNull(root.get(PARENT)));
    	
        try{
        	parentMenus = getEntityManager().createQuery(query)
                                            .getResultList();
        }catch(NoResultException e){
			// non trouvé
		}
        
        return parentMenus;
	}
	
	
	// GETTER / FLUX
	public Logger getLog(){
		return log;
	}
}